package com.scalar.chiptrack.operations.reports.actions;

import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.adaptor.Adaptor;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.reports.forms.WipInventoryForm;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;

/**
 * Created by IntelliJ IDEA.
 * Author: Krishna Prasad
 * Date: Oct 13, 2004
 * Time: 12:37:55 PM
 * To change this template use Options | File Templates.
 */

public class WipSummaryAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {

        HttpSession session = request.getSession();
        User user           = (User)session.getAttribute (SessionKeys.USER_KEY);
        String reporttype   = request.getParameter("reporttype");
        String action = request.getParameter( "action" );
        String reqFromExtUser = request.getParameter ( "reqFromExtUser" );
        WipInventoryForm wipInventoryForm = (WipInventoryForm) form;

        Workbook workbook = null;
        String fileName = "";
        if ( "true".equalsIgnoreCase ( reqFromExtUser ) )
        {
            user = (User)session.getAttribute ( SessionKeys.EXT_USER_KEY );
            if ( user == null )
            {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, request.getServletPath() + "?" + request.getQueryString());
                return (mapping.findForward ( SessionKeys.ACTION_FORWARD_KEY_EXT_LOGIN ) );
            }
        }
        else if ( user == null )
        {
            session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, request.getServletPath() + "?" + request.getQueryString());
            return (mapping.findForward ("login"));
        }

        try
        {
            if( reporttype != null && reporttype.equalsIgnoreCase("vendorinventoryreport") )
            {
                ArrayList<LabelValueBean> partNumberList = null;
                /*
                int baseProductIdInt = 0;
                ArrayList basePartNumberList = ProductDao.loadAllBaseProducts   ( null );
                try
                {
                    baseProductIdInt = Integer.parseInt( baseProductId );
                }
                catch( NumberFormatException nfe){};
                if( baseProductIdInt > 0 )
                {
                    partNumberList = ProductDao.getPartNumberByBaseProductAndPsType( Constants.LOCATION_TYPE_CLASS_STORE , baseProductIdInt );
                }

                request.setAttribute( "basePartNumberList", basePartNumberList ); */

                partNumberList = ProductDao.loadAllPartsForProcessType( Constants.LOCATION_TYPE_FINISHED_GOODS );

                request.setAttribute( "partNumberList", partNumberList );
                request.setAttribute( "vendorName", VendorDAO.checkVendorName( user.getVendorId() ) );
                return ( mapping.findForward ("vendorInventoryReport") );
            }
            else if( reporttype != null && reporttype.equalsIgnoreCase("lotrework") )
            {
                String processType              = request.getParameter( "processType" );
                ArrayList partNumberList        = null;
                ArrayList<LabelValueBean> mktgPartNumberList    = null;

                if( processType == null || "0".equalsIgnoreCase ( processType ) )
                {
                    //mktgPartNumberList = ProductDao.loadAllBaseProducts( null );
                    mktgPartNumberList = new ArrayList<LabelValueBean>();
                }
                else if( "Finished Goods".equalsIgnoreCase ( processType ) )
                {
                    partNumberList = ProductDao.loadAllFinishedGoods();
                    mktgPartNumberList = new ArrayList<LabelValueBean>();
                    FinishedGoods finishedGoods = null;
                    for( int i = 0; i < partNumberList.size(); i++ )
                    {
                        finishedGoods = ( FinishedGoods ) partNumberList.get( i );
                        mktgPartNumberList.add( new org.apache.struts.util.LabelValueBean( finishedGoods.getManufacturingPartNo(), String.valueOf( finishedGoods.getProcessStepId() ) ) );
                    }
                }
                else
                {
                    if( "Mark and Pack".equals( processType ) )
                    {
                        processType = "Mark & Pack";
                    }
                    PartNumber partNumber   = null;
                    mktgPartNumberList      = new ArrayList<LabelValueBean>();
                    partNumberList = ProductDao.getPartNumber( processType );
                    for( int i = 0; i < partNumberList.size(); i++ )
                    {
                        partNumber = ( PartNumber ) partNumberList.get( i );
                        mktgPartNumberList.add ( new org.apache.struts.util.LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                }
                request.setAttribute( "processList", getProcessList() );
                //request.setAttribute( "baseProductList", ProductDao.loadAllPartNumberfromTestToFG() );
                request.setAttribute( "mktgPartNumberSelectList", mktgPartNumberList );

            }
            else if (reporttype != null && reporttype.equalsIgnoreCase("wipVsBackLogPlanReport"))
            {
                request.setAttribute("baseProductList", NewProductDAO.loadAllBaseProducts( null, true, true ) );
                request.setAttribute( "mktPartNumberList", NewProductDAO.loadMarketingPartNumbersbyProductID( null, Constants.LOCATION_TYPE_FG, wipInventoryForm.getProductId() +"") );
                request.setAttribute( "chipSetList" , NewProductDAO.getProcessParameterValueList(null, "ChipSET1") );
                return (mapping.findForward ("wipVsBackLogPlanReport"));
            }
            else
            {
                ArrayList mktgPartNumberList = ProductDao.loadAllBaseProducts   ( null );
                request.setAttribute( "mktgPartNumberSelectList", mktgPartNumberList );

                ArrayList customerList = CustomerDAO.getAllCustomers();
                ArrayList customerSelectList = new ArrayList();
                Customer customer = new Customer();
                for( int i = 0; i < customerList.size(); i++ )
                {
                    customer = ( Customer ) customerList.get( i );
                    customerSelectList.add( customer );
                }

                ArrayList runinfoList = AdaptorRunInfo.getAdaptorRunInfoList();
                ArrayList runInfoSelectList = new ArrayList();
                Adaptor adaptor = new Adaptor();
                for( int i = 0; i < runinfoList.size(); i++ )
                {
                      adaptor = ( Adaptor )runinfoList.get( i );
                      runInfoSelectList.add( adaptor );
                }
                request.setAttribute( "customerSelectList", customerSelectList );
                request.setAttribute( "monthList", loadMonthList() );
                request.setAttribute ( "years", SalesOrderDAO.getYearList () );
                request.setAttribute("runInfoSelectList", runInfoSelectList );
            }
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        if ( "xlsWipVsBackLogPlanReport".equalsIgnoreCase( action ))
        {               
            ArrayList wipVsbacklogList = DataDumpReportsDAO.getWipVsBacklogPlanningReport ( null, wipInventoryForm.getProductId(), wipInventoryForm.getProcessstepId(), wipInventoryForm.getChipSet() );
            //ArrayList wipVsbacklogList = DataDumpReportsDAO.getWipVsBacklogPlanningReportByDate ( null, wipInventoryForm.getProductId(), wipInventoryForm.getProcessstepId(), wipInventoryForm.getChipSet(),wipInventoryForm.getFromDate(),wipInventoryForm.getToDate() );

            workbook =  DataDumpReportsHelper.getWorkbook( wipVsbacklogList, "Wip Vs BackLog Planning Report", wipInventoryForm.getFromDate(),wipInventoryForm.getToDate(),null );
            workbook = DataDumpReportsHelper.formatWipBacklog( workbook );

            /*Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put ( "processType", "0" );
            paramMap.put ( "psIds", "0"  );
            paramMap.put ( "vendor", "0"  );
            paramMap.put ( "lotCategory", "0"  );
            paramMap.put ( "asOfDate", "0" );
            paramMap.put ( "status", "0"  );
            paramMap.put ( "reportType", "ALLWITHNONVALUE" );
            paramMap.put ( "searchPartNo", "0"  );
            paramMap.put ( "defaultPrompt", "0"  );

            workbook = DataDumpReportsDAO.getWipInventoryInfoReport ( null, paramMap, workbook ); */

            fileName = "Wip Vs BackLog Planning Report_"+ DateUtil.getTimeStamp() ;

            ExcelUtils.generateExcelReport( workbook, fileName, response );
        }
        if( reporttype != null && reporttype.equalsIgnoreCase("lotrework") )
        {
            return (mapping.findForward ("lotreworkreport"));
        }
        else if( reporttype != null && "inventorysummary".equalsIgnoreCase(reporttype) )
        {
        	try
			{
                ArrayList<LabelValueBean> vendorList            = new ArrayList<LabelValueBean> ();

	        	ArrayList<Vendor> vendorTempList = VendorDAO.getAllVendors();
                for(int i=0; i <  vendorTempList.size() ; i++ )
                {
                   Vendor vendor =  ( Vendor ) vendorTempList.get ( i );
                   vendorList.add( new org.apache.struts.util.LabelValueBean ( vendor.getVendorName() , vendor.getVendorName() ) );
                }
                request.setAttribute("psTypes", NewProductDAO.loadAllProcessesStringFromDB( null ));
                request.setAttribute( "baseProductList",ProductDao.loadChipBaseProducts(null) );
                request.setAttribute( "vendorList",vendorList );
                request.setAttribute( "categoryList", getLotCategory() );
                request.setAttribute( "statusList", NewProductDAO.loadStatusList() );
			}
			catch( Exception e )
	        {
	        	e.printStackTrace();
	        }
        	return( mapping.findForward( "inventorysummary" ) );
        }
        else
        {
            return (mapping.findForward ("wipsummaryreport"));
        }

        
	} //  End of "execute" method

	private static ArrayList<LabelValueBean> loadMonthList()
    {
        ArrayList<LabelValueBean> monthList = new ArrayList<LabelValueBean>();

        monthList.add( new LabelValueBean( "January",   "1" ) );
        monthList.add( new LabelValueBean( "February",  "2" ) );
        monthList.add( new LabelValueBean( "March",     "3" ) );
        monthList.add( new LabelValueBean( "April",     "4" ) );
        monthList.add( new LabelValueBean( "May",       "5" ) );
        monthList.add( new LabelValueBean( "June",      "6" ) );
        monthList.add( new LabelValueBean( "July",      "7" ) );
        monthList.add( new LabelValueBean( "August",    "8" ) );
        monthList.add( new LabelValueBean( "September", "9" ) );
        monthList.add( new LabelValueBean( "October",   "10" ) );
        monthList.add( new LabelValueBean( "November",  "11" ) );
        monthList.add( new LabelValueBean( "December",  "12" ) );

        return monthList;
    }

    public ArrayList<LabelValueBean> getProcessList()
    {
        ArrayList<LabelValueBean> processList = new ArrayList<LabelValueBean>();
        processList.add( new org.apache.struts.util.LabelValueBean( "TEST", "TEST" ) );
        processList.add( new org.apache.struts.util.LabelValueBean( "CLASS STORE", "Class Store" ) );
        processList.add( new org.apache.struts.util.LabelValueBean( "MARK&PACK", "Mark and Pack" ) );
        processList.add( new org.apache.struts.util.LabelValueBean( "FINISHED GOODS", "Finished Goods" ) );
        return processList;
    }

    private ArrayList<LabelValueBean> getLotCategory()
    {
        ArrayList<LabelValueBean> categoryList = new ArrayList<LabelValueBean>();

        categoryList.add( new LabelValueBean( "All Categories", "0") );
        categoryList.add( new LabelValueBean( "PROD", "PROD") );
        categoryList.add( new LabelValueBean( "ENGG", "ENGG" ) );

        return categoryList;
    }

}
